import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import '../provider/user_provider.dart';
import '../router/router_utils.dart';

class AudioCallPage extends StatefulWidget {
  const AudioCallPage({super.key});

  @override
  AudioCallPageState createState() => AudioCallPageState();
}

class AudioCallPageState extends State<AudioCallPage> {
  var arguments = RouterUtils.getArgument();
  bool isCall = false; //是否拨打期间
  bool videoPlay = false; //视频是否播放
  final FijkPlayer player = FijkPlayer();
  late final Dio _dio;
  String url = "rtmp://192.168.1.9:1935/live/1001";
  String textWord = "";

  void init() async {
    await [
      Permission.microphone,
      Permission.storage,
    ].request();
    try {
      // FormData formData = FormData.fromMap({
      //   "file": await MultipartFile.fromFile(audioFilePath!),
      // });
      // Response response = await _dio.post(
      //   "http://192.168.1.9:5000/asr",
      //   data: formData,
      //   options: Options(
      //     headers: {
      //       'Content-Type': 'multipart/form-data',
      //     },
      //   ),
      // );
      // print("response======${response}");
      setState(() {
        isCall = true;
      });
      // player.setDataSource(url, autoPlay: true);
      setState(() {
        videoPlay = true;
      });
    } on Exception catch (e) {
      print('rtmp初始化失败: $e');
    }
  }

  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  void dispose() {
    super.dispose();
    player.release();
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Consumer<UserProvider>(
        builder: (context, vm, _) {
          return Stack(
            fit: StackFit.expand,
            children: [
              !videoPlay
                  ? Positioned.fill(
                      bottom: 0,
                      child: Container(
                        height: height, // 调整图片高度以适应不同设备
                        width: width,
                        decoration: const BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                                'assets/images/teacher/bg.png'), // 替换为你的图片路径
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    )
                  : Positioned.fill(
                      bottom: 0,
                      child: FijkView(
                        player: player,
                      ),
                      // child: _videoController!.value.isInitialized
                      //     ?
                      //       AspectRatio(
                      //         aspectRatio: _videoController!.value.aspectRatio,
                      //         child: VideoPlayer(_videoController!),
                      //       )
                      //     : Container(),
                    ),

              // 底部图片
              !videoPlay
                  ? Positioned(
                      bottom: 0, // 将图片放在底部
                      left: 0,
                      right: 0,
                      child: Container(
                        alignment: Alignment.center, // 居中对齐
                        child: Image.network(
                          arguments['imagePath'], // 底部图片的路径
                          fit: BoxFit.cover,
                          width: 280, // 使图片宽度与屏幕宽度相同
                          height: 590, // 使图片宽度与屏幕宽度相同
                        ),
                      ),
                    )
                  : Container(),

              // 半透明遮罩层
              Positioned.fill(
                child: Container(
                  color: Colors.black.withOpacity(0.5), // 设置遮罩层的颜色和透明度
                ),
              ),

              videoPlay
                  ? textWord != ""
                      ? Positioned(
                          bottom: 142.h, // 从顶部偏移
                          left: 0,
                          right: 0, // 添加这一行以实现水平居中
                          child: SingleChildScrollView(
                              scrollDirection: Axis.vertical,
                              child: Container(
                                constraints: const BoxConstraints(
                                  maxHeight: 300, // 设置最大高度
                                ),
                                margin: EdgeInsets.symmetric(horizontal: 30.w),
                                padding: EdgeInsets.symmetric(
                                    horizontal: 12.w, vertical: 10.w),
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.5),
                                  borderRadius: BorderRadius.circular(6.r),
                                ),
                                child: Text(
                                  textWord,
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                      fontSize: 14, color: Colors.white),
                                ),
                              )),
                        )
                      : Container()
                  : Positioned(
                      bottom: 200.h, // 从顶部偏移
                      left: 0,
                      right: 0, // 添加这一行以实现水平居中
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Column(
                          children: [
                            Text(
                              arguments['label'],
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                  fontSize: 20, color: Colors.white),
                            ),
                            const SizedBox(height: 16),
                            const Text(
                              // isCall==true?"已接通...": "正在呼叫中...",
                              "正在呼叫中...",
                              textAlign: TextAlign.center,
                              style:
                                  TextStyle(fontSize: 14, color: Colors.white),
                            ),
                          ],
                        ),
                      ),
                    ),

              Positioned(
                bottom: 60.h, // 从顶部偏移
                left: 0,
                right: 0,
                child: Row(children: [
                  // SizedBox(
                  //   width: 36.w,
                  // ),
                  // GestureDetector(
                  //   onTap: () {},
                  //   child: Image.asset("assets/images/video.png", fit: BoxFit.cover, width: 38.w)
                  // ),
                  const Spacer(),
                  GestureDetector(
                      onTap: () {
                        RouterUtils.back(context);
                      },
                      child: Container(
                        margin: EdgeInsets.symmetric(vertical: 20.w),
                        child: Image.asset("assets/images/cancelCall.png",
                            fit: BoxFit.cover, width: 56.w),
                      )),
                  const Spacer(),
                  // GestureDetector(
                  //   onTap: () {},
                  //   child: Image.asset("assets/images/audio.png", fit: BoxFit.cover, width: 38.w)
                  // ),
                  // SizedBox(
                  //   width: 36.w,
                  // ),
                ]),
              ),
            ],
          );
        },
      ),
    );
  }
}
